#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import sys
import getopt
import chardet
from cdctools import cdWalker, cdcGrep

CDROM = '/media/cdrom0'

def _smartcode(stream):
    """smart convert stream into UTF-8"""
    
    ustring = stream
    codedetect = chardet.detect(ustring)['encoding']
    print codedetect
    try:
        print ustring
        ustring = unicode(ustring, codedetect)
        print ustring
        return '%s %s' % ('', ustring.encode('utf8'))
    except:
        return u'bad unicode encode try!'
        

def usage():
    print '''pycdc使用指南：
    #将光盘内容记录为mycd1-1.cdc
    python pycdc.py -e mycd1-1.cdc
    #按关键字查询文件(-d  指定cdc文件目录)，多个关键字用‘，’分开
    python pycdc.py -k keywords'''    

def main(argv):
    cdcfile = 'cdc/mycd.cdc'
    cdcdir = 'cdc'
    try:
        opts, args = getopt.getopt(argv, 'hce:k:d:', ['help', 'command', 'cdcfile=', 'keywords=', 'cdcdir='])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit()
        elif opt in ('-e', '--cdcfile'):
            cdcfile = arg
            cdWalker(CDROM, cdcfile)
        elif opt in ('-d', '--cdcdir'):
            cdcdir = arg
        elif opt in ('-k', '--keywords'):
            keywords = arg
            cdcGrep(cdcdir, keywords)
        elif opt in ('-c', '--command'):
            cdc = PyCDC()
            cdc.cmdloop()
                            
if __name__ == '__main__':
    main(sys.argv[1:])
